package com.microframework.base.core.redis.service;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

/**
 * Redis分布式锁服务
 */
@Slf4j
@Service
public class RedisLockService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String LOCK_PREFIX = "redis_lock:";
    private static final long DEFAULT_EXPIRE = 30000L; // 默认锁过期时间30秒
    private static final long DEFAULT_WAIT = 3000L; // 默认等待时间3秒

    // 释放锁的Lua脚本
    private static final String RELEASE_LOCK_LUA = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    /**
     * 尝试获取分布式锁
     *
     * @param lockKey 锁的键
     * @param requestId 请求标识
     * @param expireTime 锁的过期时间，单位毫秒
     * @return 是否获取成功
     */
    public boolean tryLock(String lockKey, String requestId, long expireTime) {
        try {
            String key = LOCK_PREFIX + lockKey;
            Boolean result = redisTemplate.opsForValue().setIfAbsent(key, requestId, expireTime, TimeUnit.MILLISECONDS);
            return Boolean.TRUE.equals(result);
        } catch (Exception e) {
            log.error("获取分布式锁失败，key={}", lockKey, e);
            return false;
        }
    }

    /**
     * 尝试获取分布式锁，带重试机制
     *
     * @param lockKey 锁的键
     * @param requestId 请求标识
     * @param expireTime 锁的过期时间，单位毫秒
     * @param waitTime 等待时间，单位毫秒
     * @return 是否获取成功
     */
    public boolean tryLockWithRetry(String lockKey, String requestId, long expireTime, long waitTime) {
        long startTime = System.currentTimeMillis();
        while (true) {
            if (tryLock(lockKey, requestId, expireTime)) {
                return true;
            }
            if (System.currentTimeMillis() - startTime > waitTime) {
                return false;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return false;
            }
        }
    }

    /**
     * 释放分布式锁
     *
     * @param lockKey 锁的键
     * @param requestId 请求标识
     * @return 是否释放成功
     */
    public boolean releaseLock(String lockKey, String requestId) {
        try {
            String key = LOCK_PREFIX + lockKey;
            DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
            redisScript.setScriptText(RELEASE_LOCK_LUA);
            redisScript.setResultType(Long.class);
            Long result = redisTemplate.execute(redisScript, java.util.Collections.singletonList(key), requestId);
            return result != null && result > 0;
        } catch (Exception e) {
            log.error("释放分布式锁失败，key={}", lockKey, e);
            return false;
        }
    }

    /**
     * 使用默认配置尝试获取锁
     *
     * @param lockKey 锁的键
     * @param requestId 请求标识
     * @return 是否获取成功
     */
    public boolean tryLock(String lockKey, String requestId) {
        return tryLock(lockKey, requestId, DEFAULT_EXPIRE);
    }

    /**
     * 使用默认配置尝试获取锁，带重试机制
     *
     * @param lockKey 锁的键
     * @param requestId 请求标识
     * @return 是否获取成功
     */
    public boolean tryLockWithRetry(String lockKey, String requestId) {
        return tryLockWithRetry(lockKey, requestId, DEFAULT_EXPIRE, DEFAULT_WAIT);
    }
} 